import { PlayerHeadUI, PlayerHeadUIPool } from "../gameEtc/PlayerHeadUI"

@Component
export default class Appearance extends mw.Script{

    static AppearanceMap:Map<number,Appearance> = new Map()

    @mw.Property({multicast:true, replicated:true, onChanged:'onOwnerPlayerIDChanged'})
    ownerPlayerID:number
    @mw.Property({multicast:true, replicated:true, onChanged:'onWeaponCfgIDChanged'})
    weaponCfgID:number = 0
    @mw.Property({multicast:true, replicated:true, onChanged:'onOwnerPlayerNameChanged'})
    playerName:string

    ownerPlayer:Player
    weaponGameObject: mw.GameObject
    headUI:PlayerHeadUI
    pole: mw.GameObject

    init(ownerPlayerID:number){
        this.ownerPlayerID = ownerPlayerID
        Appearance.AppearanceMap.set(this.ownerPlayerID, this)
    }

    private onOwnerPlayerIDChanged(){
        Appearance.AppearanceMap.set(this.ownerPlayerID, this)
        this.ownerPlayer = Player.getPlayer(this.ownerPlayerID)

        // 播放动作弹跳动作
        let animation = this.ownerPlayer.character.loadAnimation('35411')
        animation.loop = 0
        animation.play()

        // 装备弹跳杆
        this.pole = GameObject.findGameObjectById('1F34B1EC').clone({replicates:false})
        this.ownerPlayer.character.attachToSlot(this.pole, HumanoidSlotType.Root)
        this.pole.localTransform.position = new Vector(0, 0, 30)
    }

    private onOwnerPlayerNameChanged(){
        if(!this.ownerPlayer || !this.ownerPlayer.character) return
        if(!this.headUI){
            this.headUI = PlayerHeadUIPool.get()
        }
        this.headUI.setInfo(this.ownerPlayer.character, this.playerName)
    }
    // private onWeaponCfgIDChanged(){
    //     if (!this.ownerPlayer || !this.ownerPlayer.character) return
    //     if (this.weaponGameObject) GameObjPool.despawn(this.weaponGameObject)
    //     if (this.weaponCfgID == 0) return
    //     let equipCfg = GameConfig.Weapon.getElement(this.weaponCfgID)
    //     this.weaponGameObject = SpawnManager.modifyPoolSpawn(equipCfg.GUID, GameObjPoolSourceType.Scene)
    //     if(!this.weaponGameObject) return
    //     this.weaponGameObject.setCollision(mw.CollisionStatus.Off)
    //     let [offset, rotation, scale] = util.unpackTransformByNumberArray(equipCfg.TRS)
    //     this.ownerPlayer.character.attachToSlot(this.weaponGameObject, mw.HumanoidSlotType.RightHand)
    //     this.weaponGameObject.localTransform.position = (offset)
    //     this.weaponGameObject.localTransform.rotation = (rotation)
    //     this.weaponGameObject.localTransform.scale = (scale)
    // }

    protected onDestroy(): void {
        if(SystemUtil.isClient()) {
            GameObjPool.despawn(this.weaponGameObject)
        }
        Appearance.AppearanceMap.delete(this.ownerPlayerID)
    }
}